

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Platform,
  TouchableOpacity,
  View,
  Image,
  ScrollView,
  Modal
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import Watermark from './watermark.js';
// import ImageViewer from './imageView.js';
import ImageViewer from 'react-native-transformable-image';
var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;
var ScreenHeight = Dimensions.get('window').height;

let _this;
export default class imagePicker extends Component {
  constructor(props) {
    super(props);
    _this = this;
    this.state = {
      avatarSource: null,
      show: false,
    };

  }
  onImage() {

      const options = {
          title: '请选择',
          cancelButtonTitle: '取消',
          takePhotoButtonTitle: '拍照',//调用相机拍照，''：禁止此功能
          chooseFromLibraryButtonTitle: '',//从相册中选择图片，''：禁止此功能
          quality: 0.1,
          // maxHeight:ScreenHeight/4,
          allowsEditing: false,
          noData: false,
          storageOptions: {
              skipBackup: true,
              path: 'images',
              
          }
      };
      
      ImagePicker.showImagePicker(options, (response) => {
          console.log('Response = ', response);

          if (response.didCancel) {
            console.log('User cancelled image picker');
          }
          else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
          }
          else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton);
          }
          else {
              let date = _this.getDate(new Date(), "yyyy-MM-dd hh:mm:ss");
              let params = {
                              originImagePath: response.uri,
                              watermark: [
                              {
                                  type: 1,      //文字
                                  text: "客户位置：12123143213， 34212321312312",
                              },{
                                  type: 1,      //文字
                                  text: "拍摄时间：" + date,
                              },]
                          }
              
              // You can also display the image using data:
               //let source = { uri: 'data:image/jpeg;base64,' + response.data };
               //console.warn(JSON.stringify(response));
              
            //   Watermark.addWatermark(JSON.stringify(params), (data) => {
            //       _this.setState({
            //           avatarSource: {uri: data}
            //       });
            //   });
                
                _this.setState({
                   avatarSource: {uri: response.uri}
                });
               /* console.warn(global.userid+this.props.cardName+this.props.imagePosi+'loginState');*/

                storage.load({//获取用户id
                    key: global.userid+this.props.cardName+this.props.imagePosi+'loginState',
                }).then(ret => {
                    //userId存在，获取用户对应的手势密码
                   /*console.warn(ret.imgpath);*/
                  

                });
                // _this.props.changeImgPath(response.uri);
                /*Watermark.addWatermark(params, (data) => {

                    //console.warn(JSON.stringify(data))
                    _this.setState({
                        avatarSource: {uri: data.imagePath}
                    });
                });*/
          }
      })

  }

  getDate(date, fmt) {         
    var o = {         
    "M+" : date.getMonth()+1, //月份         
    "d+" : date.getDate(), //日         
    "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时         
    "H+" : date.getHours(), //小时         
    "m+" : date.getMinutes(), //分         
    "s+" : date.getSeconds(), //秒         
    "q+" : Math.floor((date.getMonth()+3)/3), //季度         
    "S" : date.getMilliseconds() //毫秒         
    };         
    var week = {         
    "0" : "/u65e5",         
    "1" : "/u4e00",         
    "2" : "/u4e8c",         
    "3" : "/u4e09",         
    "4" : "/u56db",         
    "5" : "/u4e94",         
    "6" : "/u516d"        
    };         
    if(/(y+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));         
    }         
    if(/(E+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[date.getDay()+""]);         
    }         
    for(var k in o){         
        if(new RegExp("("+ k +")").test(fmt)){         
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
        }         
    }         
    return fmt;
}


  IsetStateFun(){
      this.setState({
          avatarSource:null
      })
  }

  _ModalShow(){
      this.setState({
          show:true
      });
  }
  _Modalhidden(){
      this.setState({
          show:false
      });
  }

  render() {
    return (
      <ScrollView style={{flexDirection:'row'}}>
          <TouchableOpacity onPress={() => {
              _this = this;
              
              //如果没有拍照
              if(!this.state.avatarSource){
                  _this.onImage()
              }else{//已拍过，点击查看图片
                
                  this._ModalShow()
                
              }
          }}
          style={{opacity:this.state.aOpacity1}}
          >
            <View>  
                <Image
                    resizeMode="stretch"
                    style={this.state.avatarSource == null ? this.props.defaultStyle : this.props.style}
                    source={this.state.avatarSource == null ? require('../images/camera.png') : this.state.avatarSource}
                    />

              {
                  this.state.avatarSource == null ? <View></View> :
                        <View style={{position:'absolute',top:10,right:10,}}>
                            <TouchableOpacity onPress={ ()=>this.props.IonImage()} style={styles.Remake}>  
                                <Text style={{color:'#fff'}}>重拍</Text>
                            </TouchableOpacity>

                            <TouchableOpacity onPress={() => { this.props.IsetState() }}
                                style={styles.delete}>  
                                <Text style={{color:'#EE902C'}}>删除</Text>
                            </TouchableOpacity>
                        </View>
              }
              
              
            </View>
          </TouchableOpacity>


            <Modal
                animationType={'slide'}
                transparent={true}
                visible={this.state.show}>
                <TouchableOpacity 
                    style={styles.ImageView}
                    activeOpacity={1}
                    onPress={() => this._Modalhidden()}
                    // 需要加一个透明度，因为和 ImageViewer 是父子级包含关系，会导致双指的点击事件冲突（TouchableOpacity双指会透明）
                    >
                    <ImageViewer
                        style={{height: (ScreenWidth-40)/ ScreenWidth * ScreenHeight, width:ScreenWidth}}
                        source={this.state.avatarSource}
                        />
                        <TouchableOpacity onPress={() => this._Modalhidden()} style={{height:30,width:30,position:'absolute',top:20,right:5}}>
                            <Image
                                style={{height: 30, width: 30}}
                                source={require('../images/close.png')}
                                                    />
                        </TouchableOpacity>
                        
                </TouchableOpacity>
            </Modal>

         </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
  },
  ImageView:{
    backgroundColor:'#000000ee',
    alignItems: 'center',  
    justifyContent:'center',  
    flex:1,
  },
  Remake:{
    backgroundColor:'#12b7f5',
    borderRadius:5,
    width:50,
    height:30,
    alignItems:'center',
    justifyContent:'center'
  },
  delete:{
    marginTop:20,
    backgroundColor:'#12b7f5',
    borderRadius:5,
    width:50,height:30,
    alignItems:'center',
    justifyContent:'center'
  }
});

